<script lang="ts" setup>
import { reactive } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { useFs } from '@fast-crud/fast-crud';

import { BaseDictApi } from '#/api/basic/base/baseDict';
import { useMessage } from '#/hooks/web/useMessage';
import { $t } from '#/locales';

import { createCrudOptions } from '../data/def-dict-crud';

interface Emits {
  (e: 'success'): void;
}

defineOptions({
  name: '导入系统字典',
  inheritAttrs: false,
});
const emit = defineEmits<Emits>();
const { createMessage } = useMessage();
const formData = reactive({
  roleId: '',
  bindEmployeeIds: [] as string[],
});

const { crudRef, crudBinding, crudExpose, selectedRowKeys } = useFs({
  createCrudOptions,
  context: formData,
});

const [Modal, modalApi] = useVbenModal({
  async onOpened() {
    selectedRowKeys.value = [];
    crudExpose.doRefresh();
  },
  onConfirm: handleSubmit,
});

async function handleSubmit() {
  try {
    modalApi.setState({ loading: true, confirmLoading: true });
    const dictIds = selectedRowKeys.value;
    if (dictIds && dictIds.length > 0) {
      await BaseDictApi.importDict(dictIds[0]);

      createMessage.success($t(`common.tips.importSuccess`));
      modalApi.close();
      emit('success');
    } else {
      createMessage.warning('请先选择字典');
    }
  } finally {
    modalApi.setState({ loading: false, confirmLoading: false });
  }
}

defineExpose(modalApi);
</script>

<template>
  <Modal title="导入系统字典" class="h-full w-full">
    <FsCrud ref="crudRef" v-bind="crudBinding" />
  </Modal>
</template>
